module.exports = (EdtApi) => {
    "use strict";
    let chatId = "", contentDocument = document;
    async function getChatId(times = 0) {
        let el = contentDocument.querySelector('div.css-py020d-DivChatHeaderContentWrapper[role="link"] a.css-1qxabns-StyledLink[href]');
        let id = el?.href?.replace('https://www.tiktok.com/@', '').replace('/', '') || '';
        if (id && id == chatId) {
            await EdtApi.sleep(50);
            if (times > 10) return id;
            times++;
            return getChatId(times);
        } else {
            return id;
        }
    }
    return {
        config: {
            friendList: 'div.css-bh4lwh-DivListContent',
            chat: '.css-d0yksp-DivChatBox',
            input: 'div.DraftEditor-root div.public-DraftEditor-content[role="textbox"]',
            msgBox: 'div.css-96mvex-DivChatMain,.css-okl125-DivChatMainContent',
            sendBtn: 'svg[data-e2e="message-send"],.css-d7yhdo-StyledSendButton',
            setting: '#main-content-messages div[data-e2e="message-input-area"]>div.css-1a4kn3-DivEditorContainer',
            tips: {
                in: '.css-6oin0b-DivChatHeader div.css-mfs62b-DivNameContainer',
                out: 'div.css-nhbyau-DivChatBottom'
            },
            placeholder: {
                selector: "div.DraftEditor-root div.public-DraftEditorPlaceholder-inner",
                update: true
            },
            extra: {//其他会触发对话框变动的情况处理
                selector: 'a.link-a11y-focus,a.css-22xkqc-StyledLink,.css-9j9jz0-DivMessageIconContainer.e1nx07zo0,.css-1btqthh-Button-StyledMessageButton,button[data-e2e="message-button"]',
                level: 20,
                delay: 800,
            },
            autoCount: 20
        },
        init(handler) {
            EdtApi.queryWait({
                selector: 'div.message-iframe iframe.w-full.h-full',
                interval: 500,
                timeout: 60000
            }).then(iframe => {
                console.log("初始化成功:::", iframe);
                if (!iframe) return;
                iframe.onload = function () {
                    console.log("iframe加载完成。", iframe);
                    handler.document = iframe.contentDocument;
                    contentDocument = iframe.contentDocument;
                    handler.initEventListener();
                };
            });
        },
        getUnread() {
            const unreadEl = contentDocument.querySelector('#app-header div[data-e2e="top-dm-icon"]>sup') || contentDocument.querySelector('a[data-e2e="nav-messages"] sup>p') || contentDocument.querySelector('button.TUXButton--secondary sup.css-rqq30d-SupBadge') || contentDocument.querySelector('#app-header div[data-e2e="inbox-icon"] sup') || contentDocument.querySelector('.text-color-TextTertiary.text-P3-Semibold>span>span');
            let count = unreadEl?.textContent || 0;
            return parseInt(count);
        },
        inputMsg(inputEl, msg) {//必须
            return new Promise((resolve) => {
                inputEl?.focus();
                contentDocument.execCommand("selectAll");
                EdtApi.sleep(20).then(() => {
                    navigator.clipboard.writeText(msg).then(() => {
                        contentDocument.execCommand("paste");
                        resolve(true);
                    }).catch(() => {
                        resolve(false);
                    });
                });
            });
        },
        getMessageList() {
            let messages = {
                in: [],
                out: [],
            }
            let item, chatItem, msgs = contentDocument.querySelectorAll(`${this.config.msgBox} div[data-e2e="chat-item"] .css-1rdxtjl-PText:not(.trans-inited)`);
            msgs?.forEach(msg => {
                chatItem = EdtApi.closest(msg, 'div[data-e2e="chat-item"]>div', 10);
                if (chatItem) {
                    item = chatItem.querySelector(".e9j91383");
                    if (item) {
                        if ("flex-end" == window.getComputedStyle(chatItem)?.alignSelf) {
                            messages.out.push(msg);
                        } else {
                            messages.in.push(msg);
                        }
                    }
                }
            });
            return messages;
        },
        getChatInfo() {
            return new Promise(async (resolve) => {
                chatId = await getChatId();
                console.log("chatId:", chatId);
                resolve({ id: chatId, isGroup: false });
            });
        },
        getText(msgBox) {
            return msgBox?.textContent || "";
        },
        getIptMsg(inputEl) {
            return inputEl?.textContent || "";
        },
        getUserInfo() {
            try {
                let userEl = contentDocument.querySelector('div.css-r0hg2a-DivSideNavContainer nav>ul.css-nwhccz-UlMainNav>li a[data-e2e="nav-profile"]');
                let avatar = userEl?.querySelector("img")?.getAttribute("src") || "";
                let userName = userEl?.getAttribute("href") || "";
                if (userName) userName = userName.replace("/", "").replace("@", "");
                if (!userName) {
                    let page_title = window.sessionStorage?.getItem('_tea_cache_duration');
                    if (page_title) page_title = JSON.parse(page_title)?.page_title;
                    if (page_title) userName = page_title.split(" ")[0];
                }
                if (!avatar) {
                    userEl = contentDocument.querySelector("#header-more-menu-icon");
                    if (userEl) avatar = window.getComputedStyle(userEl)?.getPropertyValue('background-image')?.replace('url("', '')?.replace('")', '');
                }
                return {
                    avatar,
                    userName,
                    account: userName,
                    toDataUrl: true
                };
            } catch (error) {
                return null;
            }
        }
    }
};